import java.util.Random;

/**
 * 作业:
 * 给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
 * 实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
 * 其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
 * 最终再汇总两个和, 进行相加
 * 记录程序的执行时间.
 */

public class homework {
    public static final int Default_Test_Num = 1_0000_0000;
    //普通循环:
    public static void serial(){
        long beg = System.currentTimeMillis();
        int[] nums = new int[Default_Test_Num];
        for (int i = 0 ; i < Default_Test_Num; i++){
            int rad = (int) (Math.random() * 100);
            nums[i] = rad;
        }
        long sum1 = 0;
        for (int i = 0 ; i < Default_Test_Num; i+=2){
            sum1 += nums[i];
        }
        long sum2 = 0;
        for (int i = 1 ; i < Default_Test_Num; i+=2){
            sum2 += nums[i];
        }
        //long sum = sum1 + sum2;
        long end = System.currentTimeMillis();
        System.out.println("循环执行时间:" + (end - beg) + "ms");
    }

    //利用线程:
    public static void concurrency() throws InterruptedException {
        long beg = System.currentTimeMillis();
        int[] nums = new int[Default_Test_Num];
        for (int i = 0 ; i < Default_Test_Num; i++){
            int rad = (int) (Math.random() * 100);
            nums[i] = rad;
        }
        Thread t1 = new Thread(() -> {
            int s1 = 0;
            for (int i = 0 ; i < Default_Test_Num; i+=2){
                s1 += nums[i];
            }
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            int s2 = 0;
            for (int i = 1 ; i < Default_Test_Num; i+=2){
                s2 += nums[i];
            }
        });
        t2.start();
        t1.join();
        t2.join();
        long end = System.currentTimeMillis();
        System.out.println("线程执行时间:" + (end - beg) + "ms");
    }
    public static void main(String[] args) throws InterruptedException {
        serial();
        concurrency();
    }
}
